/**
 * Created by mooshroom on 2017/8/11.
 */
/*
 * python like 的字符串模版填充函数
 * @params tmp 字符串模版 {{key}} 为要填充的地方
 * @params data 填充内容
 * 案例： StringFormat('{{name}} is {{what}}',{name:"mooshroom",what:'handsome'})  ==> 'mooshroom is handsome'
 * */

function StringFormat(tmp, data) {

    var Tmp = String(tmp)
    var soltList = []
    var eating = false
    var food = ''

    //遍历字符串取出需要填充的地方
    for (var i = 0; i < Tmp.length; i++) {
        //判断读取开始
        if (Tmp[i] === '{' && Tmp[i - 1] === "{") {
            eating = true
            continue
        }

        //判断读取结束
        if (Tmp[i] === '}' && Tmp[i + 1] === '}') {
            eating = false
            soltList.push(food)
            food = ''
            continue
        }

        //中间变量
        if (eating) {
            food += Tmp[i]
        }
    }
    var err = 'StringFormat缺少参数：', isErr = false
    //填充字符串
    soltList.forEach(function (p1, p2, p3) {
        if (data[p1] === undefined) {
            err += (p1 + ',')
            isErr = true
            return
        }
        Tmp=Tmp.replace("{{" + p1 + "}}", data[p1])
    })
    if (isErr) {
        console.error(err)
        return ''
    } else {

        return Tmp
    }

}

exports.StringFormat=StringFormat
